package com.yicong.ants.ui.circle.article;

import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.bumptech.glide.Glide;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.ImageLoader;
import com.cchao.simplelib.core.JsonHelper;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.StringHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.luck.picture.lib.entity.LocalMedia;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.circle.ArticleItem;
import com.yicong.ants.databinding.ArticleTitleEditActivityBinding;
import com.yicong.ants.manager.AppHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.ui.circle.journal.DragCallBack;
import com.yicong.ants.ui.circle.journal.OnRecyclerItemClickListener;
import com.yicong.ants.ui.common.ImageViewPagerActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author cch
 * @version 2020/8/22
 */
public class ArticleTitleEditActivity extends BaseTitleBarActivity<ArticleTitleEditActivityBinding> implements View.OnClickListener {
    boolean mIsEdit;
    List<LocalMedia> mMediaList = new ArrayList<>();
    BaseQuickAdapter<LocalMedia, BaseViewHolder> mAdapter;
    ItemTouchHelper itemTouchHelper;
    RecyclerView mRecycler;
    TextView mDeleteField;
    ArticleItem mArticleItem;
    int Max_Image = 3;
    View mAddView;

    @Override
    protected int getLayout() {
        return R.layout.article_title_edit_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("发布文章");
        if (StringHelper.isNotEmpty(getIntent().getStringExtra(Constants.Extra.JSON))) {
            mArticleItem = JsonHelper.toObject(getIntent().getStringExtra(Constants.Extra.JSON), ArticleItem.class);
            mIsEdit = true;
            mDataBind.title.setText(mArticleItem.getTitle());
            setTitleText("修改文章");
        }
        mDataBind.setClick(this);
        onLoadData();
        initViews();
    }

    private void initViews() {
        mDataBind.title.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mDataBind.titleTextLimit.setText(s.toString().length() + "/48");
            }
        });
        mDeleteField = mDataBind.deleteField;
        if (mArticleItem != null && CollectionHelper.isNotEmpty(mArticleItem.getResource())) {
            for (String s : mArticleItem.getResource()) {
                LocalMedia localMedia = new LocalMedia();
                localMedia.setParentFolderName(s);
                if (mArticleItem.getType() == 3) {
                    localMedia.setMimeType("video/mp4");
                }
                mMediaList.add(localMedia);
            }
        }

        // 最后一个添加
        LocalMedia localMedia = new LocalMedia();
        localMedia.setParentFolderName("add");
        mMediaList.add(localMedia);

        initRecyclerView();
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Circle_Aritcle_Suc:
                finish();
                break;
        }
    }

    @Override
    protected void onLoadData() {
    }

    private void initRecyclerView() {
        mRecycler = mDataBind.recycler;
        mAdapter = new BaseQuickAdapter<LocalMedia, BaseViewHolder>(R.layout.item_post_activity, mMediaList) {

            @Override
            public int getItemCount() {
                return super.getItemCount();
            }

            @Override
            protected void convert(BaseViewHolder helper, LocalMedia item) {
                UiHelper.setVisibleElseGone(helper.itemView, helper.getAdapterPosition() < Max_Image);
                UiHelper.setVisibleElseGone(helper.itemView.findViewById(R.id.play), false);
                // 隐藏 add
                String path = item.getRealPath();
                if (item.isCompressed()) {
                    path = item.getCompressPath();
                }
                if (mIsEdit && item.getParentFolderName().startsWith("http")) {
                    path = item.getParentFolderName();
                }

                ImageView imageView = helper.itemView.findViewById(R.id.image);
                imageView.setBackgroundColor(0);
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                if ("add".equals(item.getParentFolderName())) {
                    imageView.setScaleType(ImageView.ScaleType.CENTER);
                    imageView.setImageResource(R.drawable.journal_add_image);
                    imageView.setBackgroundColor(UiHelper.getColor(R.color.f4f4f4));
                    mAddView = helper.itemView;
                    return;
                }

                if (item.getMimeType().contains("video")) {
                    if (StringHelper.isNotEmpty(item.getRealPath())) {
                        Glide.with(mContext)
                            .load(Uri.fromFile(new File(item.getRealPath())))
                            .into(imageView);
                    } else {
                        Glide.with(mContext)
                            .load(item.getParentFolderName())
                            .into(imageView);
                    }
                    UiHelper.setVisibleElseGone(helper.itemView.findViewById(R.id.play), true);
                    return;
                }
                ImageLoader.loadImage(imageView, path);
            }
        };
        mRecycler.setLayoutManager(new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL));
        mRecycler.setAdapter(mAdapter);
        mDataBind.recycler.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int adapterPosition = parent.getChildAdapterPosition(view);
                if (adapterPosition > 2) {
                    outRect.top = UiHelper.dp2px(10);
                }
            }
        });

        //事件监听
        mRecycler.addOnItemTouchListener(new OnRecyclerItemClickListener(mRecycler) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                if ("add".equals(mMediaList.get(vh.getAdapterPosition()).getParentFolderName())) {
                    ImageHelper.addImage(thisActivity, Max_Image, mRecycler, mAdapter);
                    return;
                }

                if (mMediaList.size() > 1 && mMediaList.get(0).getMimeType().contains("video")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String type = "video/mp4";
                    if (mIsEdit) {
                        intent.setDataAndType(Uri.parse(mMediaList.get(0).getParentFolderName()), type);
                    } else {
                        intent.setDataAndType(Uri.fromFile(new File(mMediaList.get(0).getRealPath())), type);
                    }
                    startActivity(intent);
                    return;
                }

                List<String> list = new ArrayList<>();
                for (LocalMedia media : mMediaList) {
                    list.add(media.getCompressPath());
                }
                Router.turnTo(mContext, ImageViewPagerActivity.class)
                    .putExtra(Constants.Extra.JSON, JsonHelper.toJson(list))
                    .putExtra(Constants.Extra.Index, vh.getAdapterPosition())
                    .start();
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
                // 如果item不是最后一个，则执行拖拽
                if (vh.getLayoutPosition() != mMediaList.size() - 1) {
                    itemTouchHelper.startDrag(vh);
                }
            }
        });


        DragCallBack myCallBack = new DragCallBack(mAdapter, mMediaList);
        myCallBack.setDragListener(new DragCallBack.DragListener() {
            @Override
            public void deleteState(boolean delete) {
                if (delete) {
                    mDeleteField.setBackgroundResource(R.color.red_dark_primary);
                    mDeleteField.setText(UiHelper.getString(R.string.post_delete_tv_s));
                } else {
                    mDeleteField.setText(UiHelper.getString(R.string.post_delete_tv_d));
                    mDeleteField.setBackgroundResource(R.color.red_primary);
                }
            }

            @Override
            public void dragState(boolean start) {
                UiHelper.setVisibleElseGone(mDeleteField, start);
            }

            @Override
            public void clearView() {
//                refreshLayout();
            }
        });

        itemTouchHelper = new ItemTouchHelper(myCallBack);
        itemTouchHelper.attachToRecyclerView(mRecycler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBackPressed();
                break;
            case R.id.next:
                if (StringHelper.isEmpty(mDataBind.title.getText())) {
                    showToast("请填写标题");
                    return;
                }

                if (mMediaList.size() == 1 && !AppHelper.isDebug()) {
                    showToast("请分享图片或视频");
                    return;
                }
                if (mIsEdit) {
                    Router.turnTo(mContext, ArticleContentEditActivity.class)
                        .putExtra(Constants.Extra.Title, mDataBind.title.getText().toString())
                        .putExtra(Constants.Extra.JSON, JsonHelper.toJson(mMediaList))
                        .putExtra(Constants.Extra.JSON2, JsonHelper.toJson(mArticleItem))
                        .start();
                } else {
                    Router.turnTo(mContext, ArticleContentEditActivity.class)
                        .putExtra(Constants.Extra.Title, mDataBind.title.getText().toString())
                        .putExtra(Constants.Extra.JSON, JsonHelper.toJson(mMediaList))
                        .start();
                }
                break;
            case R.id.review:
                if (StringHelper.isEmpty(mDataBind.title)) {
                    showToast("请填写标题");
                    return;
                }

//                Dialogs.showAdReview(mContext, mStyle, mDataBind.title.getText().toString(), String.valueOf(mDataBind.imageUpload.getTag()), null);
                break;
        }
    }
}
